#/bin/bash

function set_path() {
	# 添加/删除环境变量
	# 其中将作以下更改：
	# * 修改文件 ~/.bashrc
	#
	# set_path <-a/-d> <Directory>
	# param: -a/-d         -a 添加 -d 删除
	# param: Directory     目录位置
	# return: 0            成功
	# return: 1            失败

	if [ $# -lt 2 ]; then
		${BASH_SOURCE} -l ${FUNCNAME} -a && echo -e "\033[31m[ERROR]\033[0m ${BASH_SOURCE}:${LINENO} 少于 2 个参数\n"
		return 1
	fi
	if [ "$1" != "-a" ] && [ "$1" != "-d" ]; then
		${BASH_SOURCE} -l ${FUNCNAME} -a && echo -e "\033[31m[ERROR]\033[0m ${BASH_SOURCE}:${LINENO} 函数格式: set_path <-a/-d> <Directory>\n"
		return 1
	fi

	local Param2=${2%*/}
	Param2=${2//\/\//\/}
	Param2=${Param2%*/}
	if [ "$1" = "-a" ]; then
		[ ! -d ${Param2} ] && { echo -e "\033[31m[ERROR]\033[0m ${BASH_SOURCE}:${LINENO} No such directory '${Param2}'\n";  return 1; }

		if !(grep -q -e ".*export.*PATH.*=.*${Param2}:" ~/.bashrc); then
			sudo echo "export PATH=${Param2}:\$PATH" >> ~/.bashrc || { echo -e "\033[31m[ERROR]\033[0m ${BASH_SOURCE}:${LINENO} 文件写入失败\n"; return 1; }
		fi

		(echo $PATH | grep -q -e "${Param2}") || PATH=${Param2}:$PATH
	else
		local Path=${Param2//\//\\\/}
		# \/\? 表示匹配0次或一次 \? 前面的字符
		local SedLine=`sed -n -e "/.*export.*PATH.*=.*${Path}\/\?:/=" ~/.bashrc | sed -n '1p'`
		[ ! -d ${Param2} ] && echo -e "\033[33m[WARN]\033[0m ${BASH_SOURCE}:${LINENO} 不存在的文件夹 '${Param2}'"
		if [ -n "${SedLine}" ]; then
			sudo sed -e "${SedLine}d" -i ~/.bashrc || { echo -e "\033[31m[ERROR]\033[0m ${BASH_SOURCE}:${LINENO} 文件操作失败\n"; return 1; }
		fi
		PATH=`echo $PATH | sed -e "s/${Path}://g"`
	fi

	chmod +x ${Param2}/*.sh
}

bash ./tools/bash/installation.sh && \
set_path -a $(dirname $(readlink -e ${BASH_SOURCE})) && \
echo -e "\033[35mComplete\033[0m"

